package utils

import (
	"net/http"

	"ginx/internal/global"
	"ginx/internal/global/common"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

var logger *zap.Logger = global.L

// ZapLogger 是一个使用Zap记录日志的Gin中间件
func SystemLogger(c *gin.Context, clientInfo common.ClientInfo, serviceCode int, message string) {

	// 获取系统错误信息
	ginErrMsg := c.Errors.ByType(gin.ErrorTypePrivate).String()

	// 根据状态码记录不同级别的日志
	if clientInfo.StatusCode >= http.StatusInternalServerError {
		logger.Error(
			"HTTP ERROR",
			zap.Int("status", clientInfo.StatusCode),
			zap.String("method", clientInfo.Method),
			zap.String("path", clientInfo.Path),
			zap.String("ip", clientInfo.IP),
			zap.String("latency", clientInfo.Latency),
			zap.Int("code", serviceCode),
			zap.String("message", ginErrMsg),
		)
	} else if clientInfo.StatusCode >= http.StatusBadRequest {
		logger.Warn(
			"HTTP WARNING",
			zap.Int("status", clientInfo.StatusCode),
			zap.String("method", clientInfo.Method),
			zap.String("path", clientInfo.Path),
			zap.String("ip", clientInfo.IP),
			zap.String("latency", clientInfo.Latency),
			zap.Int("code", serviceCode),
			zap.String("message", message),
		)
	} else {
		logger.Info(
			"HTTP SUCCESS",
			zap.Int("status", clientInfo.StatusCode),
			zap.String("method", clientInfo.Method),
			zap.String("path", clientInfo.Path),
			zap.String("ip", clientInfo.IP),
			zap.String("latency", clientInfo.Latency),
			zap.Int("code", serviceCode),
			zap.String("message", message),
		)
	}

}
